package youcaihuaoa.weetop.com.vm.main

import android.app.Application
import android.graphics.Bitmap
import android.graphics.drawable.Drawable
import android.text.TextUtils
import androidx.databinding.ObservableField
import api.UserServiceFactory
import com.blankj.utilcode.util.LogUtils
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import com.bumptech.glide.request.target.CustomTarget
import com.bumptech.glide.request.target.SimpleTarget
import com.bumptech.glide.request.transition.Transition
import com.luck.picture.lib.entity.LocalMedia
import com.robot.base.base.vm.GLBaseViewModel
import com.robot.base.common.api.AbstractViewModelSubscriber
import com.robot.base.common.api.UserService
import com.robot.base.configs.PrefsManager
import com.robot.base.model.SignGroupBean
import com.robot.base.util.ActivityUtils
import com.robot.base.util.LiveDataBus
import com.robot.base.util.ToastUtils
import com.robot.base.util.WifiMacUtil
import com.robot.base.utils.ChoiceImgHelper
import io.reactivex.Observable
import io.reactivex.ObservableEmitter
import io.reactivex.ObservableOnSubscribe
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.functions.Consumer
import io.reactivex.schedulers.Schedulers
import me.goldze.mvvmhabit.binding.command.BindingAction
import me.goldze.mvvmhabit.binding.command.BindingCommand
import me.goldze.mvvmhabit.http.BaseResponse
import me.goldze.mvvmhabit.http.NetworkUtil
import youcaihuaoa.weetop.com.GlApp
import youcaihuaoa.weetop.com.utils.BitmapUtils
import java.text.SimpleDateFormat
import java.util.*
import java.util.concurrent.TimeUnit
import kotlin.math.ln

class SignMapViewModel(application: Application) : GLBaseViewModel(application) {

    var signProfileBean: SignGroupBean? = null

    var workTimeField = ObservableField<String>()

    var workSignTimeField = ObservableField<String>()

    var sleepTimeField = ObservableField<String>()

    var sleepSignTimeField = ObservableField<String>()

    var currentTime = ObservableField<String>()

    var avatar = ObservableField<String>()

    var name = ObservableField<String>()

    var desc = ObservableField<String>()

    var isCanSign = ObservableField(false)

    var hasFaceSign = ObservableField(false)

    var hasWifiSign = ObservableField(false)
    val signEnableField = ObservableField(true)
    val signField = ObservableField<String>()


    var signSpaceDesc = ObservableField("不在打卡范围内")

    var lat = ""

    var lng = ""

    var address_data = ""

    val clickStartSignCommand = BindingCommand<Any>(BindingAction {
        if (isCanSign.get() == false) {
            ToastUtils.showShort("不在打卡范围内!")
            return@BindingAction
        }
        val rlStatus = signProfileBean?.kqz_data?.rl_status ?: "0"//人脸验证
        if (rlStatus == "1") {
            //开启刷脸
            doFace()
        } else {
            doSign()
        }
    })

    fun doFace() {
        ChoiceImgHelper.ChoiceOpenCamera(
            ActivityUtils.getTopActivity(),
            false,
            { result: List<LocalMedia?> ->
                val path = result[0]?.compressPath ?: ""
                GlApp.getContext()?.let {
                    Glide.with(it)
                        .asBitmap()
                        .load(path)
                        .into(object : CustomTarget<Bitmap>() {
                            override fun onResourceReady(
                                resource: Bitmap,
                                transition: Transition<in Bitmap>?
                            ) {
                                doSign(BitmapUtils.bitmapToBase64(resource))
                            }

                            override fun onLoadCleared(placeholder: Drawable?) {

                            }

                        })
                }
            },
            {})
    }


    fun doSign() {
        val wifiStatus = signProfileBean?.kqz_data?.wifi_status ?: "0"//wifi验证
        val addressStatus = signProfileBean?.kqz_data?.address_status ?: "0"//地址验证
        val params = mutableMapOf("group_id" to signProfileBean?.kqz_data?.id)

        if (wifiStatus == "1") {
            //wifi验证
            val wifiMacAddress = WifiMacUtil.getBBSid(GlApp.getContext())
            if (TextUtils.isEmpty(wifiMacAddress)) {
                ToastUtils.showShort("不存在wifi")
                return
            }
            params["wifi_mac"] = wifiMacAddress
        }
        if (addressStatus == "1") {
            params["address_data"] = address_data
            params["address_lng"] = lng
            params["address_lat"] = lat
        }
        UserServiceFactory.userDk(params.toMap())
            .subscribe(object : AbstractViewModelSubscriber<BaseResponse<Any>>(this) {
                override fun onNext(t: BaseResponse<Any>) {
                    ToastUtils.showShort("打卡成功")
                    LiveDataBus.get().with("sign_success").postValue("")
                }
            })
    }

    fun doSign(base64: String) {
        val wifiStatus = signProfileBean?.kqz_data?.wifi_status ?: "0"//wifi验证
        val addressStatus = signProfileBean?.kqz_data?.address_status ?: "0"//地址验证
        val params = mutableMapOf("group_id" to signProfileBean?.kqz_data?.id)
        params["rl_image_path"] = base64
        LogUtils.d("base64----${base64}")
        if (wifiStatus == "1") {
            //wifi验证
            val wifiMacAddress = WifiMacUtil.getBBSid(GlApp.getContext())
            if (TextUtils.isEmpty(wifiMacAddress)) {
                ToastUtils.showShort("不存在wifi")
                return
            }
            params["wifi_mac"] = wifiMacAddress
            LogUtils.d("wifimac----${wifiMacAddress}")
        }
        if (addressStatus == "1") {
            params["address_data"] = address_data
            params["address_lng"] = lng
            params["address_lat"] = lat
        }
        LogUtils.e("requestParams----${params}")

        UserServiceFactory.userDk(params.toMap())
            .subscribe(object : AbstractViewModelSubscriber<BaseResponse<Any>>(this) {
                override fun onNext(t: BaseResponse<Any>) {
                    ToastUtils.showShort("打卡成功")
                    LiveDataBus.get().with("sign_success").postValue("")
                    finish()
                }
            })
    }


    fun initSignProfile(bean: SignGroupBean?) {
        signProfileBean = bean
        workTimeField.set("上班时间：${bean?.kqz_data?.sbdk_time ?: ""}")
        workSignTimeField.set("打卡时间：${bean?.sbdk_data?.times ?: ""}")
        sleepTimeField.set("下班时间：${bean?.kqz_data?.xbdk_time ?: ""}")
        sleepSignTimeField.set("打卡时间：${bean?.xbdk_data?.times ?: ""}")
        val userInfo = PrefsManager.getUserInfo()
        avatar.set(userInfo.head_img)
        name.set(userInfo.user_name)
        desc.set(userInfo.department_name + "-${userInfo.job_name}")
        val faceStatus = signProfileBean?.kqz_data?.rl_status ?: "0"//wifi验证
        val wifiStatus = signProfileBean?.kqz_data?.wifi_status ?: "0"//wifi验证
        hasFaceSign.set(faceStatus == "1")
        hasWifiSign.set(wifiStatus == "1")

        signEnableField.set(signProfileBean?.sbdk_data == null || signProfileBean?.xbdk_data == null)
        signField.set(
            if (signProfileBean?.sbdk_data == null) {
                "上班打卡"
            } else {
                "下班打卡"
            }
        )
        initTime()
    }

    fun checkIsCanSign(isCanSign: Boolean, lat: String, lng: String, address_data: String) {
        this.lat = lat
        this.lng = lng
        this.address_data = address_data
        signSpaceDesc.set(if (isCanSign) "您已进入打卡范围" else "不在打卡范围内")
        this.isCanSign.set(isCanSign)
    }


    fun initTime() {
        Observable.create(object : ObservableOnSubscribe<String> {
            private var format = ""
            private lateinit var simpleDateForma: SimpleDateFormat;
            private lateinit var date: Date
            override fun subscribe(emitter: ObservableEmitter<String>) {
                Schedulers.io().createWorker().schedulePeriodically(Runnable() {
                    date = Date(System.currentTimeMillis());
                    simpleDateForma = SimpleDateFormat("HH:mm:ss");
                    format = simpleDateForma.format(date);
                    emitter.onNext(format);
                }, 0, 1000, TimeUnit.MILLISECONDS);
            }
        }).observeOn(AndroidSchedulers.mainThread())
            .subscribe { currentTime.set(it); };
    }
}